package com.snail.auth.service;

import cn.hutool.http.Header;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.snail.common.core.constant.Constants;
import com.snail.common.core.constant.SecurityConstants;
import com.snail.common.core.domain.R;
import com.snail.common.core.utils.ServletUtils;
import com.snail.common.core.utils.StringUtils;
import com.snail.common.core.utils.ip.IpUtils;
import com.snail.system.api.RemoteLogService;
import com.snail.system.api.domain.SysLoginInfo;
import com.snail.thirdparty.api.RemoteThirdPartyService;
import com.snail.thirdparty.api.dto.IpLocalDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 记录日志方法
 *
 * @author snail
 */
@Component
public class SysRecordLogService {
    @Autowired
    private RemoteLogService remoteLogService;

    @Autowired
    private RemoteThirdPartyService remoteThirdPartyService;

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息内容
     * @return
     */
    public void recordLogininfor(String username, String status, String message) {
        SysLoginInfo logininfor = new SysLoginInfo();
        logininfor.setUserName(username);
        logininfor.setIpaddr(IpUtils.getIpAddr());
        UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getHeader(ServletUtils.getRequest(), Header.USER_AGENT.toString()));
        logininfor.setSystemOs(userAgent.getPlatform().getName());
        logininfor.setBrowser(IpUtils.getBrowser());
        R<IpLocalDto> r = remoteThirdPartyService.getIpLocal(logininfor.getIpaddr(), SecurityConstants.INNER);
        if (r.isOk()) {
            IpLocalDto data = r.getData();
            logininfor.setLocation(data.getProvince() + "  " + data.getCity());
        } else {
            logininfor.setLocation(IpUtils.getLocation());
        }
        logininfor.setMsg(message);
        // 日志状态
        if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
            logininfor.setStatus(Constants.LOGIN_SUCCESS_STATUS);
        } else if (Constants.LOGIN_FAIL.equals(status)) {
            logininfor.setStatus(Constants.LOGIN_FAIL_STATUS);
        }
        logininfor.setAccessTime(LocalDateTime.now());
        logininfor.setTenantId(ServletUtils.getHeader(ServletUtils.getRequest(),SecurityConstants.TENANT_ID));
        remoteLogService.saveLogininfor(logininfor, SecurityConstants.INNER);
    }
}
